<!DOCTYPE HTML>
<html lang="zh-CN">


<head><meta name="generator" content="Hexo 3.8.0">
    <meta charset="utf-8">
    <meta name="keywords" content="Retain&amp;Release解读, Swift, iOS, Python">
    <meta name="description" content="群组欢迎加入群组,闲聊工作&amp;amp;技术&amp;amp;问题等

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;iOS通过引用计数(Reference Counting)机制来管理内存,当一个对象">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>Retain&amp;Release解读 | waitwalker</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">
    <style type="text/css">
        
    </style>

    <script src="/libs/jquery/jquery-2.2.0.min.js"></script>
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>


<body>

<!--导航-->

<header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    <!---->
                    <!--<img src="/medias/logo.png" class="logo-img" alt="LOGO">-->
                    <!---->
                    <span class="logo-span">waitwalker</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fa fa-navicon"></i></a>
<ul class="right">
    
    <li class="hide-on-med-and-down">
        <a href="/" class="waves-effect waves-light">
            
            <i class="fa fa-home"></i>
            
            <span>首页</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/tags" class="waves-effect waves-light">
            
            <i class="fa fa-tags"></i>
            
            <span>标签</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/categories" class="waves-effect waves-light">
            
            <i class="fa fa-bookmark"></i>
            
            <span>分类</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/archives" class="waves-effect waves-light">
            
            <i class="fa fa-archive"></i>
            
            <span>归档</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/about" class="waves-effect waves-light">
            
            <i class="fa fa-user-circle-o"></i>
            
            <span>关于</span>
        </a>
    </li>
    
    <li class="hide-on-med-and-down">
        <a href="/friends" class="waves-effect waves-light">
            
            <i class="fa fa-address-book"></i>
            
            <span>友情链接</span>
        </a>
    </li>
    
    <li>
        <a href="#searchModal" class="modal-trigger waves-effect waves-light">
            <i id="searchIcon" class="fa fa-search" title="搜索"></i>
        </a>
    </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">waitwalker</div>
        <div class="logo-desc">
            
            Life is measured by thought and action not by time.
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li>
            <a href="/" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-home"></i>
                
                首页
            </a>
        </li>
        
        <li>
            <a href="/tags" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-tags"></i>
                
                标签
            </a>
        </li>
        
        <li>
            <a href="/categories" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-bookmark"></i>
                
                分类
            </a>
        </li>
        
        <li>
            <a href="/archives" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-archive"></i>
                
                归档
            </a>
        </li>
        
        <li>
            <a href="/about" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-user-circle-o"></i>
                
                关于
            </a>
        </li>
        
        <li>
            <a href="/friends" class="waves-effect waves-light">
                
                <i class="fa fa-fw fa-address-book"></i>
                
                友情链接
            </a>
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://github.com/waitwalker" class="waves-effect waves-light" target="_blank">
                <i class="fa fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>

        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #0f9d58;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://github.com/waitwalker" class="github-corner tooltipped hide-on-med-and-down" target="_blank" data-tooltip="https://github.com/waitwalker" data-position="left" data-delay="50">
    <svg viewbox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/>
    </svg>
</a>
        
    </nav>

</header>





<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/6.jpg')">
    <div class="container">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <div class="description center-align post-title">
                        Retain&amp;Release解读
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>



<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 20px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Runtime/" target="_blank">
                                <span class="chip bg-color">Runtime</span>
                            </a>
                        
                            <a href="/tags/底层/" target="_blank">
                                <span class="chip bg-color">底层</span>
                            </a>
                        
                            <a href="/tags/源码/" target="_blank">
                                <span class="chip bg-color">源码</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fa fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/Runtime源码解读/" class="post-category" target="_blank">
                                Runtime源码解读
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                <div class="post-date info-break-policy">
                    <i class="fa fa-calendar-minus-o fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2019-04-22
                </div>

                
				
				
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="fa fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <p><strong>群组</strong><br><strong>欢迎加入群组,闲聊工作&amp;技术&amp;问题等</strong></p>
<p><img src="https://github.com/waitwalker/Resources/blob/master/Flutter/group/flutter_development_0923.JPG?raw=true" width="350" height="480" align="center"></p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;iOS通过引用计数(Reference Counting)机制来管理内存,当一个对象被创建出来时,它的引用计数从0增加到1,当有外部对象对它进行强引用时,也就是当有额外的指针指向它时,它的引用计数会+1,当该对象收到一条release消息时,它的引用计数会-1;当对象的引用计数为0时,对象将被释放,对象指向的内存被回收.</p>
<h3 id="Retain"><a href="#Retain" class="headerlink" title="Retain"></a>Retain</h3><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;引用计数的增加和减少的原理是什么样的呢?下面我们从源码中来分析一下.以Person *p1 = [[Person alloc]init]为例;</p>
<p>在之前文章中我们总结了一个<a href="[https://waitwalker.cn/2019/04/10/objc-object%E8%A7%A3%E8%AF%BB/](https://waitwalker.cn/2019/04/10/objc-object%E8%A7%A3%E8%AF%BB/">对象的初始化过程可以总结为分配内存空间并且初始化isa_t结构的过程</a>),我们再把源码贴出来一下(objc_object.h文件中):</p>
<pre><code>
inline void

objc_object::initIsa(Class cls, bool nonpointer, bool hasCxxDtor)

{

assert(!isTaggedPointer());

// 不是tagged pointer

if (!nonpointer) {

isa.cls = cls;

} else {

assert(!DisableNonpointerIsa);

assert(!cls-&gt;instancesRequireRawIsa());

isa_t newisa(0);

#if SUPPORT_INDEXED_ISA

assert(cls-&gt;classArrayIndex() &gt; 0);

newisa.bits = ISA_INDEX_MAGIC_VALUE;

// isa.magic is part of ISA_MAGIC_VALUE

// isa.nonpointer is part of ISA_MAGIC_VALUE

newisa.has_cxx_dtor = hasCxxDtor;

newisa.indexcls = (uintptr_t)cls-&gt;classArrayIndex();

#else

newisa.bits = ISA_MAGIC_VALUE;

// isa.magic is part of ISA_MAGIC_VALUE

// isa.nonpointer is part of ISA_MAGIC_VALUE

newisa.has_cxx_dtor = hasCxxDtor;

newisa.shiftcls = (uintptr_t)cls &gt;&gt; 3;

#endif

// This write must be performed in a single store in some cases

// (for example when realizing a class because other threads

// may simultaneously try to use the class).

// fixme use atomics here to guarantee single-store and to

// guarantee memory order w.r.t. the class index table

// ...but not too atomic because we don&#39;t want to hurt instantiation

isa = newisa;

}

}

</code></pre><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;可以看到初始化isa的过程中,并没对保存引用计数的成员变量extra_rc进行操作,我们可以得出一个初步结论,对象在第一次创建的时候,其extra_rc=0;我们知道对象的所有权修饰符默认是strong.其源对象的引用计数的增加也在于有strong指针指向时,即我们示例中的p1强指针,指向了[[Person alloc]init],使[[Person alloc]init]的引用计数从0增加到了1,*p1对象的引用计数此时也就是1了.</p>
<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;之前我们查看ivar相关接口的时候已经对objc_storeStrong有了初步了解,我们来看看objc_storeStrong的调用栈:</p>
<pre><code>
// strong

void

objc_storeStrong(id *location, id obj)

{

id prev = *location;

if (obj == prev) {

return;

}

objc_retain(obj);

*location = obj;

objc_release(prev);

}

</code></pre><p>看到objc_storeStrong()入口函数内是先调用了objc_retain()新值,然后objc_release()了旧值.</p>
<p>retain调用:</p>
<pre><code>
// retain

__attribute__((aligned(16)))

id

objc_retain(id obj)

{

if (!obj) return obj;

if (obj-&gt;isTaggedPointer()) return obj;

return obj-&gt;retain();

}

inline id

objc_object::retain()

{

assert(!isTaggedPointer());

if (fastpath(!ISA()-&gt;hasCustomRR())) {

return rootRetain();

}

return ((id(*)(objc_object *, SEL))objc_msgSend)(this, SEL_retain);

}

ALWAYS_INLINE id

objc_object::rootRetain()

{

return rootRetain(false, false);

}

</code></pre><p>最终调用的是ALWAYS_INLINE id objc_object::rootRetain(bool tryRetain, bool handleOverflow){}函数</p>
<pre><code>
// MARK: - rootRetian

ALWAYS_INLINE id

objc_object::rootRetain(bool tryRetain, bool handleOverflow)

{

if (isTaggedPointer()) return (id)this;

bool sideTableLocked = false;

bool transcribeToSideTable = false;

isa_t oldisa;

isa_t newisa;

do {

transcribeToSideTable = false;

// 首先通过LoadExclusive()加载旧的oldisa

oldisa = LoadExclusive(&amp;isa.bits);

newisa = oldisa;

if (slowpath(!newisa.nonpointer)) {

ClearExclusive(&amp;isa.bits);

if (!tryRetain &amp;&amp; sideTableLocked) sidetable_unlock();

if (tryRetain) return sidetable_tryRetain() ? (id)this : nil;

else return sidetable_retain();

}

// don&#39;t check newisa.fast_rr; we already called any RR overrides

if (slowpath(tryRetain &amp;&amp; newisa.deallocating)) {

ClearExclusive(&amp;isa.bits);

if (!tryRetain &amp;&amp; sideTableLocked) sidetable_unlock();

return nil;

}

uintptr_t carry;

// 引用计数加1

newisa.bits = addc(newisa.bits, RC_ONE, 0, &amp;carry); // extra_rc++

// 判断extra_rc位数能否保存引用计数

if (slowpath(carry)) {

// extra_rc溢出;handleOverflow=false

// newisa.extra_rc++ overflowed

if (!handleOverflow) {

ClearExclusive(&amp;isa.bits);

return rootRetain_overflow(tryRetain);

}

// 有溢出 将extra_rc置为最大值的一半

// Leave half of the retain counts inline and

// prepare to copy the other half to the side table.

if (!tryRetain &amp;&amp; !sideTableLocked) sidetable_lock();

sideTableLocked = true;

transcribeToSideTable = true;

newisa.extra_rc = RC_HALF;

newisa.has_sidetable_rc = true;

}

} while (slowpath(!StoreExclusive(&amp;isa.bits, oldisa.bits, newisa.bits)));//存储

// 有溢出 将另一半的引用计数拷贝到side table里面

if (slowpath(transcribeToSideTable)) {

// Copy the other half of the retain counts to the side table.

sidetable_addExtraRC_nolock(RC_HALF);

}

if (slowpath(!tryRetain &amp;&amp; sideTableLocked)) sidetable_unlock();

// 返回自身

return (id)this;

}

</code></pre><p>其逻辑过程:</p>
<p>1.1)首先调用LoadExclusive()函数获取旧isa,然后赋值给新的isa实例:newisa;</p>
<p>1.2)调用addc()函数,将extra_rc++;</p>
<p>1.3)调用StoreExclusive()更新isa的引用计数,最后返回更新后的isa;这个过程没有处理溢出情况</p>
<p>2.1)如果if (slowpath(carry)) {}为真,判断handleOverflow是否为false,为false,调用rootRetain_overflow()处理溢出逻辑</p>
<pre><code>
NEVER_INLINE id

objc_object::rootRetain_overflow(bool tryRetain)

{

return rootRetain(tryRetain, true);

}

</code></pre><p>rootRetain_overflow()内部调用的还是ALWAYS_INLINE id objc_object::rootRetain(bool tryRetain, bool handleOverflow)()函数,只是第二个参数handleOverflow传的是true.所以走到:</p>
<pre><code>
// 有溢出 将extra_rc置为最大值的一半

// Leave half of the retain counts inline and

// prepare to copy the other half to the side table.

if (!tryRetain &amp;&amp; !sideTableLocked) sidetable_lock();

sideTableLocked = true;

transcribeToSideTable = true;

newisa.extra_rc = RC_HALF;

newisa.has_sidetable_rc = true;

</code></pre><p>2.2)将extra_rc值置为最大值的一半,更新has_sidetable_rc标记为true,即sideTable中存储了引用计数.</p>
<p>2.3)调用StoreExclusive()更新isa的引用计数</p>
<p>2.4)将将另一半的引用计数拷贝到side table里面</p>
<pre><code>
// 有溢出 将另一半的引用计数拷贝到side table里面

if (slowpath(transcribeToSideTable)) {

// Copy the other half of the retain counts to the side table.

sidetable_addExtraRC_nolock(RC_HALF);

}

// MARK: - 将一些引用计数保存在side table中

// Move some retain counts to the side table from the isa field.

// Returns true if the object is now pinned.

bool

objc_object::sidetable_addExtraRC_nolock(size_t delta_rc)

{

assert(isa.nonpointer);

SideTable&amp; table = SideTables()[this];

size_t&amp; refcntStorage = table.refcnts[this];

size_t oldRefcnt = refcntStorage;

// isa-side bits should not be set here

assert((oldRefcnt &amp; SIDE_TABLE_DEALLOCATING) == 0);

assert((oldRefcnt &amp; SIDE_TABLE_WEAKLY_REFERENCED) == 0);

if (oldRefcnt &amp; SIDE_TABLE_RC_PINNED) return true;

uintptr_t carry;

size_t newRefcnt =

addc(oldRefcnt, delta_rc &lt;&lt; SIDE_TABLE_RC_SHIFT, 0, &amp;carry);

if (carry) {

refcntStorage =

SIDE_TABLE_RC_PINNED | (oldRefcnt &amp; SIDE_TABLE_FLAG_MASK);

return true;

}

else {

refcntStorage = newRefcnt;

return false;

}

}

</code></pre><p>之前我们提到过sideTable:</p>
<pre><code>
// MARK: - sideTabel

struct SideTable {

spinlock_t slock;

RefcountMap refcnts;将另一半的引用计数拷贝到side table里面

weak_table_t weak_table;

SideTable() {

memset(&amp;weak_table, 0, sizeof(weak_table));

}

~SideTable() {

_objc_fatal(&quot;Do not delete SideTable.&quot;);

}

void lock() { slock.lock(); }

void unlock() { slock.unlock(); }

void forceReset() { slock.forceReset(); }

// Address-ordered lock discipline for a pair of side tables.

template&lt;HaveOld, HaveNew&gt;

static void lockTwo(SideTable *lock1, SideTable *lock2);

template&lt;HaveOld, HaveNew&gt;

static void unlockTwo(SideTable *lock1, SideTable *lock2);

};

</code></pre><p>sideTable有三个成员变量:spinlock_t(自旋锁),RefcountMap(保存引用计数hash表),weak_table_t(保存weak指针hash表);</p>
<p>2.5)返回对象自身</p>
<p>以上就是retain的源码实现逻辑,思路还是很清晰.其中alloc/new/copy/mutableCopy会增加引用计数.</p>
<h3 id="Release"><a href="#Release" class="headerlink" title="Release"></a>Release</h3><p>release可以理解为retain的”逆向操作”,其入口函数:</p>
<pre><code>
// MARK: - release

__attribute__((aligned(16)))

void

objc_release(id obj)

{

if (!obj) return;

if (obj-&gt;isTaggedPointer()) return;

return obj-&gt;release();

}

// Equivalent to calling [this release], with shortcuts if there is no override

inline void

objc_object::release()

{

assert(!isTaggedPointer());

if (fastpath(!ISA()-&gt;hasCustomRR())) {

rootRelease();

return;

}

((void(*)(objc_object *, SEL))objc_msgSend)(this, SEL_release);

}

</code></pre><p>可以看到release函数最终调用的是ALWAYS_INLINE bool objc_object::rootRelease(bool performDealloc, bool handleUnderflow){};并且默认是没有引用计数溢出的情况.</p>
<pre><code>
ALWAYS_INLINE bool

objc_object::rootRelease(bool performDealloc, bool handleUnderflow)

{

if (isTaggedPointer()) return false;

bool sideTableLocked = false;

isa_t oldisa;

isa_t newisa;

retry:

do {

// 首先加载旧的isa

oldisa = LoadExclusive(&amp;isa.bits);

// 将旧的isa赋值给newisa

newisa = oldisa;

if (slowpath(!newisa.nonpointer)) {

ClearExclusive(&amp;isa.bits);

if (sideTableLocked) sidetable_unlock();

return sidetable_release(performDealloc);

}

// don&#39;t check newisa.fast_rr; we already called any RR overrides

uintptr_t carry;

// 将extra_rc减1

newisa.bits = subc(newisa.bits, RC_ONE, 0, &amp;carry); // extra_rc--

// 如果有越界的情况 即extra_rc &lt; 0,走underflow

if (slowpath(carry)) {

// don&#39;t ClearExclusive()

goto underflow;

}

} while (slowpath(!StoreReleaseExclusive(&amp;isa.bits,

oldisa.bits, newisa.bits)));//更新isa的extra_rc

if (slowpath(sideTableLocked)) sidetable_unlock();

return false;

underflow:

// newisa.extra_rc-- underflowed: borrow from side table or deallocate

// abandon newisa to undo the decrement

newisa = oldisa;

// 先判断isa的has_sidetable_rc是否为true

if (slowpath(newisa.has_sidetable_rc)) {

if (!handleUnderflow) {

ClearExclusive(&amp;isa.bits);

// 调用rootRelease_underflow,处理越界情况

return rootRelease_underflow(performDealloc);

}

// Transfer retain count from side table to inline storage.

if (!sideTableLocked) {

ClearExclusive(&amp;isa.bits);

sidetable_lock();

sideTableLocked = true;

// Need to start over to avoid a race against

// the nonpointer -&gt; raw pointer transition.

goto retry;

}

// 从side table中获取引用计数

// Try to remove some retain counts from the side table.

size_t borrowed = sidetable_subExtraRC_nolock(RC_HALF);

// To avoid races, has_sidetable_rc must remain set

// even if the side table count is now zero.

if (borrowed &gt; 0) {

// 如果borrowed(side table)的值大于1,将extra_rc中的引用计数赋值给extra_rc

// Side table retain count decreased.

// Try to add them to the inline count.

newisa.extra_rc = borrowed - 1; // redo the original decrement too

bool stored = StoreReleaseExclusive(&amp;isa.bits,

oldisa.bits, newisa.bits);

if (!stored) {

// Inline update failed.

// Try it again right now. This prevents livelock on LL/SC

// architectures where the side table access itself may have

// dropped the reservation.

isa_t oldisa2 = LoadExclusive(&amp;isa.bits);

isa_t newisa2 = oldisa2;

if (newisa2.nonpointer) {

uintptr_t overflow;

newisa2.bits =

addc(newisa2.bits, RC_ONE * (borrowed-1), 0, &amp;overflow);

if (!overflow) {

stored = StoreReleaseExclusive(&amp;isa.bits, oldisa2.bits,

newisa2.bits);

}

}

}

if (!stored) {

// Inline update failed.

// Put the retains back in the side table.

sidetable_addExtraRC_nolock(borrowed);

goto retry;

}

// Decrement successful after borrowing from side table.

// This decrement cannot be the deallocating decrement - the side

// table lock and has_sidetable_rc bit ensure that if everyone

// else tried to -release while we worked, the last one would block.

sidetable_unlock();

return false;

}

else {

// 如果side table中值为空,则执行dealloc

// Side table is empty after all. Fall-through to the dealloc path.

}

}

// Really deallocate.

if (slowpath(newisa.deallocating)) {

ClearExclusive(&amp;isa.bits);

if (sideTableLocked) sidetable_unlock();

return overrelease_error();

// does not actually return

}

newisa.deallocating = true;

if (!StoreExclusive(&amp;isa.bits, oldisa.bits, newisa.bits)) goto retry;

if (slowpath(sideTableLocked)) sidetable_unlock();

__sync_synchronize();

if (performDealloc) {

((void(*)(objc_object *, SEL))objc_msgSend)(this, SEL_dealloc);

}

return true;

}

</code></pre><p>逻辑过程:</p>
<p>1.1)调用LoadExclusive()函数,获取旧的isa,赋值给新的newisa</p>
<p>1.2)调用subc()函数,将extra_rc减1,如果carry有越界情况,走到2.1)</p>
<p>1.3)调用StoreReleaseExclusive()函数,更新返回isa</p>
<p>2.1)carry有越界,说明side table保存了引用计数,并且has_sidetable_rc=true</p>
<p>2.2)调用rootRelease_underflow()函数,传入参数handleUnderflow=true</p>
<p>2.3)调用sidetable_subExtraRC_nolock()获取引用计数,side table的引用计数大于0,将side table中的引用计数减1后赋值给extra_rc;否则走3.1)</p>
<p>2.4)调用StoreReleaseExclusive()函数,更新返回isa</p>
<p>3.1)side table中的引用计数为0,则调用dealloc方法</p>
<pre><code>
// Really deallocate.

if (slowpath(newisa.deallocating)) {

ClearExclusive(&amp;isa.bits);

if (sideTableLocked) sidetable_unlock();

return overrelease_error();

// does not actually return

}

newisa.deallocating = true;

if (!StoreExclusive(&amp;isa.bits, oldisa.bits, newisa.bits)) goto retry;

if (slowpath(sideTableLocked)) sidetable_unlock();

__sync_synchronize();

if (performDealloc) {

((void(*)(objc_object *, SEL))objc_msgSend)(this, SEL_dealloc);

}

</code></pre><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;release总结下来就是,先将extra_rc减1,如果extra_rc=0,查看side table中是否有引用计数,有则将side table中值减1后赋值给extra_rc;side table中没有值,说明引用计数为0,调用dealloc函数,整体逻辑思路也是很清晰的.</p>
<h3 id="RetainCount"><a href="#RetainCount" class="headerlink" title="RetainCount"></a>RetainCount</h3><p>retainCount是获取对象的引用计数.</p>
<pre><code>
// MARK: - 获取对象的引用计数

inline uintptr_t

objc_object::rootRetainCount()

{

if (isTaggedPointer()) return (uintptr_t)this;

sidetable_lock();

isa_t bits = LoadExclusive(&amp;isa.bits);

ClearExclusive(&amp;isa.bits);

if (bits.nonpointer) {

// 引用计数 = 1 + extra_rc

uintptr_t rc = 1 + bits.extra_rc;

// 如果side table中有值

if (bits.has_sidetable_rc) {

// 再加上side table中的引用计数

rc += sidetable_getExtraRC_nolock();

}

sidetable_unlock();

return rc;

}

sidetable_unlock();

return sidetable_retainCount();

}

</code></pre><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;先LoadExclusive()获取isa,将extra_rc加1赋值给rc,然后判断has_sidetable_rc,side table中是否有引用计数,有的话,再加上side table中的引用计数,然后返回.</p>
<h3 id="编译后源码库"><a href="#编译后源码库" class="headerlink" title="编译后源码库"></a>编译后源码库</h3><p><strong>编译后的源码放在<a href="https://github.com/waitwalker/Runtime" target="_blank" rel="noopener">Github</a>, 如果对你有帮助,请给一个star吧!</strong></p>
<h3 id="博客地址-amp-相关文章"><a href="#博客地址-amp-相关文章" class="headerlink" title="博客地址&amp;相关文章"></a>博客地址&amp;相关文章</h3><p><strong>博客地址:</strong> <a href="https://waitwalker.github.io/">https://waitwalker.github.io/</a></p>
<p>系列文章:</p>
<p><a href="https://waitwalker.github.io/2019/04/08/Runtime%E6%BA%90%E7%A0%81%E7%BC%96%E8%AF%91/">1. Runtime源码编译</a></p>
<p><a href="https://waitwalker.github.io/2019/04/10/objc-object%E8%A7%A3%E8%AF%BB/">2. objc_object解读</a></p>
<p><a href="https://waitwalker.github.io/2019/04/12/Method%E8%A7%A3%E8%AF%BB/">3. Method解读</a></p>
<p><a href="https://waitwalker.github.io/2019/04/15/Class%E8%A7%A3%E8%AF%BB/">4. Class解读</a></p>
<p><a href="https://waitwalker.github.io/2019/04/15/Ivar-objc-property-t-Protocol%E8%A7%A3%E8%AF%BB/">5. Ivar objc_property_t Protocol解读</a></p>
<p><a href="https://waitwalker.github.io/2019/04/18/Block解读/">6. Block解读</a></p>
<p><a href="http://waitwalker.cn/2019/04/22/Retain-Release解读/" target="_blank" rel="noopener">7. Retain&amp;Release解读</a></p>
<p><a href="http://waitwalker.cn/2019/04/23/Autorelease解读/" target="_blank" rel="noopener">8. Autorelease解读</a></p>
<p><a href="http://waitwalker.cn/2019/04/24/Weak解读/" target="_blank" rel="noopener">9. Weak解读</a></p>
<p><a href="http://waitwalker.cn/2019/04/25/msgSend-解读/" target="_blank" rel="noopener">10. msgSend()解读</a></p>

            </div>
            <hr>

            
            <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.88rem;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-large waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fa fa-close"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>
            

            <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    <div class="social-share" data-disabled="qzone" data-wechat-qrcode-helper="<p>微信里点“发现”->“扫一扫”二维码便可查看分享。</p>"></div>
    
</div>

<script src="/libs/share/js/social-share.min.js"></script>

            <div class="reprint">
                <p>
                    <span class="reprint-tip">
                        <i class="fa fa-exclamation-circle"></i>&nbsp;&nbsp;转载请注明:
                    </span>
                    <a href="https://waitwalker.github.io" class="b-link-green">waitwalker</a>
                    <i class="fa fa-angle-right fa-lg fa-fw text-color"></i>
                    <a href="/2019/04/22/Retain-Release解读/" class="b-link-green">Retain&amp;Release解读</a>
                </p>
            </div>
        </div>
    </div>

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6 overflow-policy" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fa fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2019/04/23/Autorelease解读/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/8.jpg" class="responsive-img" alt="Autorelease解读">
                        
                        <span class="card-title">Autorelease解读</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">群组欢迎加入群组,闲聊工作&amp;技术&amp;问题等

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Autorelease翻译过来就是自动释放,什么是自动释放,怎么自动释放,什么时候自</div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="fa fa-clock-o fa-fw icon-date"></i>2019-04-23
                        </span>
                        <span class="publish-author">
                            
                            <i class="fa fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Runtime源码解读/" class="post-category" target="_blank">
                                    Runtime源码解读
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Runtime/" target="_blank">
                        <span class="chip bg-color">Runtime</span>
                    </a>
                    
                    <a href="/tags/底层/" target="_blank">
                        <span class="chip bg-color">底层</span>
                    </a>
                    
                    <a href="/tags/源码/" target="_blank">
                        <span class="chip bg-color">源码</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6 overflow-policy" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fa fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2019/04/18/Block解读/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/13.jpg" class="responsive-img" alt="Block解读">
                        
                        <span class="card-title">Block解读</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">群组欢迎加入群组,闲聊工作&amp;技术&amp;问题等

Block定义&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;看过&lt;&lt;Objective-C高级编程iOS与OS X多线</div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="fa fa-clock-o fa-fw icon-date"></i>2019-04-18
                            </span>
                        <span class="publish-author">
                            
                            <i class="fa fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Runtime源码解读/" class="post-category" target="_blank">
                                    Runtime源码解读
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Runtime/" target="_blank">
                        <span class="chip bg-color">Runtime</span>
                    </a>
                    
                    <a href="/tags/底层/" target="_blank">
                        <span class="chip bg-color">底层</span>
                    </a>
                    
                    <a href="/tags/源码/" target="_blank">
                        <span class="chip bg-color">源码</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>
</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: waitwalker<br />'
            + '作者: waitwalker<br />'
            + '链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>

    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="fa fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fa fa-list"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            // headingsOffset: -205,
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).slideUp(500);
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).slideDown(500);
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>
    

</main>


<footer class="page-footer bg-color">
    <div class="container row center-align">
        <div class="col s12 m8 l8 copy-right">
            本站在原作者&copy;<a href="https://blinkfox.github.io/" target="_blank">Blinkfox</a>基于
            <a href="https://hexo.io/" target="_blank">Hexo</a> 的
            <a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">hexo-theme-matery</a>主题基础上搭建.

            

            
			
                <br>
                
                <span id="busuanzi_container_site_pv">
                    <i class="fa fa-heart-o"></i>
                    本站总访问量 <span id="busuanzi_value_site_pv" class="white-color"></span>
                </span>
                
                
                <span id="busuanzi_container_site_uv">
                    <i class="fa fa-users"></i>
                    次,&nbsp;访客数 <span id="busuanzi_value_site_uv" class="white-color"></span> 人.
                </span>
                
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis"><!---->
<a href="https://github.com/waitwalker" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
    <i class="fa fa-github"></i>
</a>

<a href="https://twitter.com/284485487" class="tooltipped" target="_blank" data-tooltip="Twitter联系我" data-position="top" data-delay="50">
    <i class="fa fa-twitter"></i>
</a>

<a href="https://www.facebook.com/profile.php?id=100003684945279" class="tooltipped" target="_blank" data-tooltip="Twitter联系我" data-position="top" data-delay="50">
    <i class="fa fa-facebook"></i>
</a>

<a href="https://t.me/joinchat/Ej0o0A1ntlq5ZFIMzzO5Pw" class="tooltipped" target="_blank" data-tooltip="Twitter联系我" data-position="top" data-delay="50">
    <i class="fa fa-telegram"></i>
</a>

<a href="https://www.weibo.com/1789419613/profile?topnav=1&wvr=6&is_all=1" class="tooltipped" target="_blank" data-tooltip="Twitter联系我" data-position="top" data-delay="50">
    <i class="fa fa-weibo"></i>
</a>


<!--原来-->
<!---->
    <!--<a href="mailto:waitwalker@163.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">-->
        <!--<i class="fa fa-envelope-open"></i>-->
    <!--</a>-->
<!---->

<!---->
    <!--<a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=284485487" class="tooltipped" data-tooltip="QQ联系我: 284485487" data-position="top" data-delay="50">-->
        <!--<i class="fa fa-qq"></i>-->
    <!--</a>-->
<!---->

<!---->
    <!--<a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">-->
        <!--<i class="fa fa-rss"></i>-->
    <!--</a>-->
<!----></div>
    </div>
</footer>

<div class="progress-bar"></div>


<!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fa fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字" class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
<!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fa fa-angle-up"></i>
    </a>
</div>


<script src="/libs/materialize/materialize.min.js"></script>
<script src="/libs/masonry/masonry.pkgd.min.js"></script>
<script src="/libs/aos/aos.js"></script>
<script src="/libs/scrollprogress/scrollProgress.min.js"></script>
<script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
<script src="/js/matery.js"></script>

<!-- Global site tag (gtag.js) - Google Analytics -->




    <script async src="/libs/others/busuanzi.pure.mini.js"></script>


</body>
</html>